/**
 * File    : ChangePassword.java
 * Created : 2008-10-15
 * By      : LuHuiguo
 */
package com.luhuiguo.sso.web.pages.secure;

import java.security.Principal;

import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.RequestGlobals;

import com.luhuiguo.sso.service.UserManager;
import com.luhuiguo.sso.web.model.Passwords;

/**
 * @author LuHuiguo
 * @version $Id: ChangePassword.java 19 2008-10-18 15:59:28Z LuHuiguo $
 * 
 */
public class ChangePassword {

	@Inject
	private Messages messages;

	@Inject
	private RequestGlobals requestGlobals;

	@Inject
	private UserManager userManager;

	@Component(id = "changePasswordForm")
	private BeanEditForm changePasswordForm;

	@Property
	private Passwords passwords;
	
	@SuppressWarnings("unused")
	@Property
	@Persist(PersistenceConstants.FLASH)
	private String message;	

	@OnEvent(value = Form.VALIDATE_FORM, component = "changePasswordForm")
	void onValidateForm() {
		if (!StringUtils.equals(passwords.getNewPassword(), passwords
				.getConfirmPassword())) {
			passwords.setNewPassword(null);
			changePasswordForm.recordError(messages.get("password-mismatch"));
		}
		if (!userManager.validatePassword(getUsername(), passwords
				.getOldPassword())) {
			changePasswordForm.recordError(messages.get("incorrect-password"));
		}
	}

	public String getUsername() {
		Principal principal = requestGlobals.getHTTPServletRequest()
				.getUserPrincipal();
		return principal == null ? "" : principal.getName();
	}

	@OnEvent(value = Form.SUCCESS, component = "changePasswordForm")
	Object onSuccess() {
		try {
			userManager.updatePassword(getUsername(), passwords
					.getNewPassword());
			message = messages.get("password-changed");			
		} catch (Exception e) {
			changePasswordForm.recordError(e.getMessage());
		}
		return null;
	}

}
